package com.maddox.relax.bluetooth

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Message
import androidx.databinding.DataBindingUtil
import com.maddox.relax.R
import com.maddox.relax.databinding.ActivityBluetoothServerBinding
import com.maddox.relax.util.LogUtil
import java.lang.Exception
import java.util.*
import kotlin.concurrent.thread

/**
 * @author Maadox
 * 蓝牙服务端,用于接收连接传输数据
 */
@SuppressWarnings("all")
class BluetoothServerActivity : AppCompatActivity() {

    lateinit var bluetoothAdapter: BluetoothAdapter

    //接收到的连接  可以保持一个不断传送数据
    lateinit var bluetoothSocket: BluetoothSocket

    //监听线程
    private lateinit var acceptThread: AcceptThread

    lateinit var bd:ActivityBluetoothServerBinding

    //两台蓝牙设备使用相同的UUID连接
    companion object {
        val SERVICE_NAME = "00001101-0000-1000-8000-00805F9B34FB"
    }

    //消息处理
    private val handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            bd.deviceInfo.text = msg.obj as String
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bd = DataBindingUtil.setContentView(this,R.layout.activity_bluetooth_server)
        initView()
    }

    private fun initView() {
        bd.header.toolbarBack.setOnClickListener {
            acceptThread.cancel()
            finish()
        }
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        val address = bluetoothAdapter.address
        LogUtil.d("当前设备地址:$address")
        makeDeviceDiscover()
        //开始监听
        acceptThread = AcceptThread()
        acceptThread.start()
    }


    private inner class AcceptThread : Thread() {

        private val mmServerSocket: BluetoothServerSocket? by lazy(LazyThreadSafetyMode.NONE) {
            bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(
                bluetoothAdapter.name,
                UUID.fromString(SERVICE_NAME)
            )
        }
        var shouldLoop = true

        override fun run() {
            LogUtil.d("服务端开始监听接入设备")

            while (shouldLoop) {
                val socket: BluetoothSocket? = try {
                    mmServerSocket?.accept()
                } catch (e: Exception) {
                    LogUtil.d("监听蓝牙连接异常:${e.message}")
                    shouldLoop = false
                    null
                }
                LogUtil.d("接收到客户端连接")
                //只允许一次接入一个蓝牙设备
//                cancel()
                socket?.also {
                    //管理连接
                    managerMyConnectedSocket(it)
//                    mmServerSocket?.close()
//                    shouldLoop = false
                }

            }
        }

        fun cancel() {
            try {
                mmServerSocket?.close()
                shouldLoop = false
            } catch (e: Exception) {
                LogUtil.d("已获取一个连接,停止继续监听")
            }
        }

        //接收到数据,进行回复
        private fun managerMyConnectedSocket(it: BluetoothSocket) {
            bluetoothSocket = it
            thread {
                try {
                    val inputStream = it.inputStream
                    val outputStream = it.outputStream
                    var bufferBytes = ByteArray(1024)
                    var bufferLength = 0
                    while (true) {
                        bufferLength = inputStream.read(bufferBytes)
                        if (bufferLength != -1) {
                            val result = String(bufferBytes, 0, bufferLength)
                            val message = Message()
                            message.obj = result
                            handler.sendMessage(message)
                        }
                        //自动回复
                        outputStream.write("${Date()}已经收到消息".toByteArray())

                    }
                } catch (e: Exception) {
                    LogUtil.d("接收数据异常:${e.message}")
                }
            }.start()

        }


    }

    //将当前设备处于可检测时间设置为10分钟
    private fun makeDeviceDiscover() {
        val discoverableIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE).apply {
            putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600)
        }
        startActivity(discoverableIntent)
    }
}